package com.jiuzhou.surery.service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;

import com.jiuzhou.surery.exception.StorageException;

@Service
public class FileSystemStorageService implements StorageService {

    private final Path rootLocation = Path.of("survey-uploads");

    @Override
    public void init() {
        try {
            // 确保目录存在且可写
            if (!Files.exists(rootLocation)) {
                Files.createDirectories(rootLocation);
            }
            
            // 检查目录是否可写
            if (!Files.isWritable(rootLocation)) {
                throw new StorageException("上传目录不可写: " + rootLocation.toString());
            }
        } catch (IOException e) {
            throw new StorageException("无法初始化存储目录: " + e.getMessage(), e);
        }
    }

    @Override
    public String store(MultipartFile file) {
        // 确保目录已初始化
        if (!Files.exists(rootLocation)) {
            init();
        }
        
        if (file.isEmpty()) {
            throw new StorageException("文件为空，上传失败");
        }
        
        String filename = file.getOriginalFilename();
        if (filename == null) {
            throw new StorageException("上传失败: 文件名为空");
        }
        
        if (!filename.contains(".")) {
            throw new StorageException("无效文件名: " + filename);
        }

        String extension = filename.substring(filename.lastIndexOf(".")).toLowerCase();
        if (!isImageExtensionAllowed(extension)) {
            throw new StorageException("仅允许jpeg, jpg, png, gif格式文件: " + extension);
        }
        
        String newFilename = UUID.randomUUID().toString() + extension;

        try {
            Files.copy(file.getInputStream(), this.rootLocation.resolve(newFilename));
        } catch (Exception e) {
            throw new StorageException("上传失败: " + filename + ", 错误: " + e.getMessage(), e);
        }
        
        return newFilename;
    }

    private boolean isImageExtensionAllowed(String extension) {
        return ".jpg".equals(extension) || ".jpeg".equals(extension) || 
               ".png".equals(extension) || ".gif".equals(extension);
    }

    @Override
    public void deleteAll() {
        FileSystemUtils.deleteRecursively(rootLocation.toFile());
    }

    @Override
    public Resource loadAsResource(String filename) {
        try {
            Path file = rootLocation.resolve(filename);
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() && resource.isReadable()) {
                return resource;
            } else {
                throw new StorageException("无法读取文件: " + filename);
            }
        } catch (IOException e) {
            throw new StorageException("无法读取文件: " + filename + ", 错误: " + e.getMessage(), e);
        }
    }
}